package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    private final IUserService userService;
    private final StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> BLOG_LIKE_SCRIPT;
    static {
        BLOG_LIKE_SCRIPT = new DefaultRedisScript<>();
        BLOG_LIKE_SCRIPT.setLocation(new ClassPathResource("blog_like.lua"));
        BLOG_LIKE_SCRIPT.setResultType(Long.class);
    }
    @Override
    public Result queryHotBlog(Integer current) {
        // TODO 同理，其也应该交给redis
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        // TODO 应该把这个经常查询的数据交给redis
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            blog.setIsLike(false);
            return;
        }
        Long userId = userDTO.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            return Result.fail("请先登录！");
        }
        Long userId = userDTO.getId();
        String blogLikeKey = RedisConstants.BLOG_LIKED_KEY + id;
        Long result = stringRedisTemplate.execute(
                BLOG_LIKE_SCRIPT,
                Collections.emptyList(),
                blogLikeKey,
                userId.toString(),
                String.valueOf(System.currentTimeMillis())
        );
        if (result == null) {
            return Result.fail("未知错误");
        }
        boolean isSuccess = false;
        if(result == 1)
            //TODO 后面需要改成RabbitMQ操作，数据库操作太慢了，甩给另一个消息队列去实行
            isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
        else
            isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<String> ids = top5.stream().map(String::valueOf).collect(Collectors.toList());
        Stream<UserDTO> userDTOList = userService.queryTop5ByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok(userDTOList);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
